package com.demo.webapp.views.freemarker.directive.core;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.demo.common.StringUtils;

import freemarker.core.Environment;
import freemarker.core.Environment.TemplateDirectiveBodyEx;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * 自定义指令: 分页
 * 该分页自定义指令需要满足对象
 * @author ryuu.kk
 *
 */
public class LinkDirective extends UrlDirective {

	@SuppressWarnings("rawtypes")
	@Override
	public void preWriter(Environment env, TemplateDirectiveBodyEx bodyEx,
			TemplateModel[] loopVars, SimpleHash hash, Map params)
			throws IOException, TemplateException {
		// 生成URL地址
		super.preWriter(env, bodyEx, loopVars, hash, params);
		String title = getString("title", params, "");
		hash.put("title", title);
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	protected String processSource(String source, SimpleHash hash, Map params) {
		
		if (StringUtils.isEmpty(source)) {
			int type = 0;
			try {
				type = getInteger("type", params, 0);
			} catch (TemplateModelException e) {
			}
			switch(type) {
			case 1:
				// javascript
				source = "<script src='${url}' type='text/javascript'></script>";
				break;
			case 2:
				// stylesheet
				source = "<link href='${url}' type='text/css' rel='stylesheet' />";
				break;
			default :
				// a
				source = "<a href='${url}' title='${title}'>${title}</a>";
			}
		} 
		return source;
	}
	
	@Override
	public void afterInvoke(Writer writer) {
		// nothing.
	}
}
